package com.atguigu.flink0624.chapter08;

import com.atguigu.flink0624.bean.UserBehavior;
import com.atguigu.flink0624.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Date;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/16 15:43
 */
public class Flink02_Project_High_UV {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        env
            .readTextFile("input/UserBehavior.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new UserBehavior(Long.valueOf(data[0]),
                                        Long.valueOf(data[1]),
                                        Integer.valueOf(data[2]),
                                        data[3],
                                        Long.parseLong(data[4]) * 1000);
            })
            .filter(ub -> "pv".equals(ub.getBehavior()))
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ub, ts) -> ub.getTimestamp())
            )
            .keyBy(UserBehavior::getBehavior)
            .window(TumblingEventTimeWindows.of(Time.minutes(30)))
            .process(new ProcessWindowFunction<UserBehavior, String, String, TimeWindow>() {
                
                private MapState<Long, Object> userIdState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    userIdState = getRuntimeContext()
                        .getMapState(new MapStateDescriptor<Long, Object>("userIdState", Long.class, Object.class));
                }
                
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<UserBehavior> elements,
                                    Collector<String> out) throws Exception {
                    userIdState.clear();
                    
                    for (UserBehavior ub : elements) {
                        userIdState.put(ub.getUserId(), null);
                    }
                    
                    List<Long> ids = AtguiguUtil.toList(userIdState.keys());
                    Date start = new Date(ctx.window().getStart());
                    Date end = new Date(ctx.window().getEnd());
                    out.collect(start + "  " + end + "  " + ids.size());
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
